import React, {MutableRefObject, useEffect, useState} from 'react';
import {Button, message, Popconfirm, Space, Switch, Table, Tag} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import {deletePower, getPower,updateEnable} from "../../../api/power";
import withModal from "../../../components/WithModal";
import RoleForm from "../Role/RoleForm";
import PowerForm from "./PowerForm";
import {FormInstance} from "antd/es/form";

interface DataType {
    key: React.ReactNode;
    name: string;
    age: number;
    address: string;
    children?: DataType[];
}


const data: DataType[] = [
    {
        key: 1,
        name: 'John Brown sr.',
        age: 60,
        address: 'New York No. 1 Lake Park',
        children: [
            {
                key: 11,
                name: 'John Brown',
                age: 42,
                address: 'New York No. 2 Lake Park',
            },
            {
                key: 12,
                name: 'John Brown jr.',
                age: 30,
                address: 'New York No. 3 Lake Park',
                children: [
                    {
                        key: 121,
                        name: 'Jimmy Brown',
                        age: 16,
                        address: 'New York No. 3 Lake Park',
                    },
                ],
            },
            {
                key: 13,
                name: 'Jim Green sr.',
                age: 72,
                address: 'London No. 1 Lake Park',
                children: [
                    {
                        key: 131,
                        name: 'Jim Green',
                        age: 42,
                        address: 'London No. 2 Lake Park',
                        children: [
                            {
                                key: 1311,
                                name: 'Jim Green jr.',
                                age: 25,
                                address: 'London No. 3 Lake Park',
                            },
                            {
                                key: 1312,
                                name: 'Jimmy Green sr.',
                                age: 18,
                                address: 'London No. 4 Lake Park',
                            },
                        ],
                    },
                ],
            },
        ],
    },
];

// rowSelection objects indicates the need for row selection
const rowSelection: TableRowSelection<DataType> = {
    onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
    },
};

const Index: React.FC = () => {
    const [checkStrictly, setCheckStrictly] = useState(false);
    const [title, setTitle] = useState("增加权限");
    const [id, setId] = useState(0);
    const [parentId, setParentId] = useState(0);
    const [visiable, setVisiable] = useState(false);
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            name: 'Edward King 0',
            age:32,
            address: 'London, Park Lane no. 0',
        },
        {
            key: '1',
            name: 'Edward King 1',
            age: 32,
            address: 'London, Park Lane no. 1',
        },
    ]);
    const [powerList, setPowerList] = useState<DataType[]>([]);

    const columns: ColumnsType<DataType> = [
        {
            title: '权限名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '权限类型',
            dataIndex: 'type',
            key: 'type',
            width: '12%',
            render: (_,record:any)=>
                dataSource.length >= 1 ? (
                    <Tag color={record.type==1?"magenta":"volcano"}>{record.type==1?"菜单":"按钮"}</Tag>

                ) : null,
        },
        {
            title: '权限路径',
            dataIndex: 'url',
            width: '30%',
            key: 'url',
        },
        {
            title: '是否可用',
            dataIndex: 'enable',
            width: '30%',
            render: (_, record:any) =>

                dataSource.length >= 1 ? (
                    <Switch checkedChildren="开启" unCheckedChildren="关闭"
                            key={record.enable}
                            onClick={()=>handleEnable(record.id)}
                            defaultChecked={record.enable}
                    />
                ) : null,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record: any ) =>
                dataSource.length >= 1 ? (
                    <div>
                        <Button  type="primary" onClick={()=>{open(record.id)}}>新增</Button>
                        <Button  type="primary" style={{marginLeft:20}} onClick={()=>{openEdit(record.id)}}>修改</Button>
                        <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.id)} >
                            <Button type="primary"  danger  style={{marginLeft:20}}>删除</Button>
                        </Popconfirm>
                    </div>
                ) : null,
        },
    ];

    useEffect(() => {
        getPowerList()
    }, []);

    const handleEnable = (id:number)=>{
        updateEnable(id).then(res=>{
            if(res.data.code==1)message.success(res.data.msg)
        })
    }
    const handleDelete = (id:number)=>{
        deletePower(id).then(res=>{
            if(res.data.code===1){
                message.success(res.data.msg)
                getPowerList()
            }
        })
    }
    const open = (id:number) => {
        setId(0)
        setParentId(id)
        setTitle("新增权限")
        setVisiable(true)
    }
    const openEdit = (id:number) => {
        setId(id)
        setTitle("修改权限")
        setVisiable(true)
    }
    const afterSubmit = () => {
        getPowerList()
        close()
    }
    //点击确定提交表单
    const submit = (ref: MutableRefObject<FormInstance>) => {
        ref.current.submit();
    };

    const close = () => {
        setVisiable(false)
    }


    const getPowerList = ()=>{
        getPower().then((res:any)=>{
            if(res.data.code===1){
                console.log(res.data.data)
                setPowerList(res.data.data)
            }
        })
    }
    const PowerFormModal = withModal({title}, {afterSubmit,id,parentId})(React.forwardRef(PowerForm));

    return (
        <>

            <Button onClick={()=>open(0)} type="primary" style={{ marginBottom: 16 }}>
                新增
            </Button>
            <PowerFormModal visible={visiable} onCancel={close} onOk={submit}></PowerFormModal>
            <Table
                columns={columns}
                rowSelection={{ ...rowSelection, checkStrictly }}
                rowKey ={(powerList:any)=>powerList.id}
                dataSource={powerList}
            />
        </>
    );
};

export default Index;
